<?php defined('SYSPATH') or die('No direct script access.');

class Task_Queue
{

	/* 
	 * Adds a task to the master task queue
	 * 
	 * @param string  The controller to call
	 * @param string  The controller's method to call
	 * @param string  An array of parameters to use in the method. Key/Value array required
	 * @param string  The priority number of this task. Range is 1-10, higher priority is executed before lower priority
	 *                Tasks with the same priority in the queue are executed in FIFO order
	 *
	 * @return boolean
	 *
	 */
	public static function add($controller_name, $method_name, $parameters = array(), $priority = 5, $application_path = '')
	{
		if ($priority < 1 OR $priority > 10)
		{
			Log::add('error', 'The priority of the task was out of range!');
			return FALSE;
		}

		$application_path = (empty($application_path)) ? APPPATH : $application_path;
		$old_module_list = Config::item('core.modules');
		Config::set('core.modules', array_merge($old_module_list, array($application_path)));

		// Make sure the controller name and method are valid
		if (Kohana::auto_load($controller_name))
		{
			// Only add it to the queue if the controller method exists
			if (Config::item('queue.validate_methods') AND !method_exists($controller_name, $method_name))
			{
				Log::add('error', 'The method '.$controller_name.'::'.$method_name.' does not exist.');
				return FALSE;
			}

			// Add the action to the run queue with the priority
			$task = new Task_Model();
			$task->set_fields(
				array(
					'application'  => $application_path,
					'class'        => $controller_name,
					'method'       => $method_name,
					'params'       => serialize($parameters),
					'priority'     => $priority
				)
			);
			$task->save();

			// Restore the module list
			Config::set('core.modules', $old_module_list);

			return TRUE;
		}

		Log::add('error', 'The class '.$controller_name.' does not exist.');
		return FALSE;
	}
}